package com.wondream.myframework.app.common.view;

import com.wondream.myframework.app.common.excel.CfssPoiExporter;
import com.wondream.myframework.app.common.excel.cache.ExcelTemplateCache;
import com.wondream.myframework.app.common.excel.domain.CfssExcelTemplate;
import com.wondream.myframework.app.common.exception.BusinessExeceptionCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@NoArgsConstructor
public class CfssExcelView extends CfssAbstractView {

    public static String VIEW = "CfssExcelView";
    public static final String TEMPLATE = "template";
    private static final String DATE_FORMAT = "yyyy-MM-dd";

    @Value("${spring.profiles.active:null}")
    private String active;

    @Override
    public String getView(){
        return VIEW;
    }

    protected boolean generatesDownloadContent(){
        return true;
    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        CfssExcelTemplate cfssExcelTemplate = null;
        try {
            cfssExcelTemplate = (CfssExcelTemplate) model.get("template");
        } catch (Exception e) {
            throw BusinessExeceptionCode.SYS_ERROR.exp();
        }

        XSSFWorkbook workbook = this.createWorkbook(cfssExcelTemplate);
        this.buildExcelDocument(cfssExcelTemplate, workbook);
        response.setContentType("application/vnd.ms-excel");
    }

    private XSSFWorkbook createWorkbook(CfssExcelTemplate cfssExcelTemplate) {
        try {
            InputStream in = null;
            if (null != this.active && this.active.equals("prod")) {
                in = ExcelTemplateCache.getTemplateStream(cfssExcelTemplate.getTemplatePath());
            } else {
                in = Thread.currentThread().getContextClassLoader().getResourceAsStream(cfssExcelTemplate.getTemplatePath());
                if (null == in) {
                    in = CfssExcelView.class.getResourceAsStream(cfssExcelTemplate.getTemplatePath());
                }
                in = new ByteArrayInputStream(IOUtils.toByteArray(in));
            }
            return new XSSFWorkbook((InputStream) in);
        } catch (Exception e) {
            e.printStackTrace();
            throw BusinessExeceptionCode.SYS_ERROR.exp();
        }
    }

    protected void renderWorkbook(Workbook workbook, CfssExcelTemplate cfssExcelTemplate, HttpServletRequest request, HttpServletResponse response) throws Exception{
        String filename = cfssExcelTemplate.getFilename() + DateTime.now().toString("yyyy-MM-dd")+".xlsx";
        if (isIE(request)) {
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
        } else {
            filename = new String(filename.getBytes(StandardCharsets.UTF_8.name()), "ISO-8859-1");
        }
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("content-disposition", "attachment;filename="+filename);
        ServletOutputStream out = response.getOutputStream();
        out.flush();
        IOUtils.closeQuietly(out);
        if (workbook instanceof Closeable) {
            IOUtils.closeQuietly(workbook);
        }
    }

    private void buildExcelDocument(CfssExcelTemplate cfssExcelTemplate, XSSFWorkbook workbook) throws Exception{
        CfssPoiExporter.export(workbook, cfssExcelTemplate.getData());
    }
}
